<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2005/12/06 08:43:35 $)
// $RCSfile: activedirectory.login.php,v $ : $Revision: 1.3 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Initialization function. You can connect to your database etc over here.
*/
function loginShareInit()
{
	global $loginshare;

	$loginshare->moduleloaded = true;
}

/**
* Authorize a user based on email and password
*/
function loginShareAuthorize($username, $password)
{
	global $dbCore, $_SWIFT, $loginshare, $settings;

	$_loginshare = $settings->getSection("loginshare");

	// Try the connection
	$_connection = ldap_connect($_loginshare["adhostname"], $_loginshare["adport"]);
//	echo "Connecting to LDAP Server: ".$_loginshare["adhostname"].":".$_loginshare["adport"]."<BR />";
	if (!$_connection)
	{
//		echo "Failed to Connect!<BR />";
		return false;
	} else {
//		echo "Connected!<BR />";
	}

	// and One Server to Bind them...
	if (!ldap_set_option($_connection, LDAP_OPT_PROTOCOL_VERSION, 3))
	{
//		echo "Failed to set Protocol Version<BR />";
	}

	if (!ldap_set_option($_connection, LDAP_OPT_REFERRALS, 0))
	{
//		echo "Failed to set Referrals<BR />";
	}

	$_bindstatus = false;
	if (ldap_bind($_connection, $_loginshare["adrdn"], $_loginshare["adpassword"]))
	{
		$_bindstatus = true;
//		echo "Binded to: ".$_loginshare["adrdn"].", PASS: ".$_loginshare["adpassword"]."<BR />";
	}

	if (!$_bindstatus)
	{
		@ldap_close($_connection);
//		echo "UNABLE TO BIND TO (". $_connection ."): ".$_loginshare["adrdn"].", PASS: ".$_loginshare["adpassword"]."<BR />";
		return false;
	}

	// By now we should have binded with the server
	$_ldapresults = ldap_search($_connection, $_loginshare["adbasedn"], "(&(samaccountname=" . trim(preg_replace( "/[^a-zA-Z0-9\-\_@\.]/", "" , $username)) . "))", array("samaccountname", "proxyAddresses", "mail", "distinguishedname", "displayName"), 0, 0, 10);
	if (!$_ldapresults)
	{
		return false;
	}

	$_resultcount = ldap_count_entries($_connection, $_ldapresults);
	$_results = ldap_get_entries($_connection, $_ldapresults);
	if (!$_results || !$_resultcount)
	{
		return false;
	}

	ldap_free_result($_ldapresults);
	ldap_close($_connection);

	// By now we should have the user details
	$_fullname = $_results[0]["displayname"][0];
	$_username = $_results[0]["samaccountname"][0];
	$_distinguishedname = $_results[0]["distinguishedname"][0];
	$_maillist = array();
	if (!empty($_results[0]["mail"][0]))
	{
		$_maillist[] = $_results[0]["mail"][0];
	}
	if (_is_array($_results[0]["proxyaddresses"]))
	{
		foreach ($_results[0]["proxyaddresses"] as $key=>$val)
		{
			if (is_numeric($key))
			{
				$_email = strtolower($val);
				if (substr($_email, 0, 5) == "smtp:")
				{
					$_maillist[] = substr($_email, 5);
				} else {
					$_maillist[] = $_email;
				}
			}
		}
	}

	foreach ($_maillist as $key=>$val)
	{
		if (isValidEmail($val))
		{
			$_primaryemail = $val;
			break;
		}
	}

	// By now we have just the data, but we havent validated this user yet... we need to do that to make sure he supplied the correct password
	unset($_connection);
	$_connection = ldap_connect($_loginshare["adhostname"], $_loginshare["adport"]);
//	echo "Connecting to LDAP Server (AGAIN): ".$_loginshare["adhostname"].":".$_loginshare["adport"]."<BR />";
	if (!$_connection)
	{
//		echo "Failed to Connect!<BR />";
		return false;
	} else {
//		echo "Connected!<BR />";
	}

	if (!ldap_set_option($_connection, LDAP_OPT_PROTOCOL_VERSION, 3))
	{
//		echo "Failed to set Protocol Version<BR />";
	}

	if (!ldap_set_option($_connection, LDAP_OPT_REFERRALS, 0))
	{
//		echo "Failed to set Referrals<BR />";
	}

	$_userbindstatus = false;
	if (@ldap_bind($_connection, $_distinguishedname, $password))
	{
		$_userbindstatus = true;
//		echo "User Binded to: ".$_loginshare["adrdn"].", PASS: ".$_loginshare["adpassword"]."<BR />";
	}

	if (!$_userbindstatus)
	{
//		echo "UNABLE TO USER BIND TO (". $_connection ."): ".$_loginshare["adrdn"].", PASS: ".$_loginshare["adpassword"]."<BR />";
		@ldap_close($_connection);
		return false;
	}

	// By now we have authenticated this user.
	$userid = getLoginShareUser(LOGINAPI_ACTIVEDIRECTORY, $_username);
	if (!$userid)
	{
		// Not registered, Register him
		$userid = insertUser(true, $_primaryemail, md5($password), $_SWIFT["tgroup"]["regusergroupid"], LOGINAPI_ACTIVEDIRECTORY, $_username, $_fullname, $_SWIFT["tgroup"]["languageid"], 0, false, 1, true, true);

		foreach ($_maillist as $key=>$val)
		{
			if ($key != 0 && isValidEmail($val))
			{
				insertUserEmail($userid, $val);
			}
		}
	}

	if (!$userid)
	{
		return false;
	}

	$_swiftuser = $loginshare->loadSWIFTUser($userid);
	if (!$_swiftuser)
	{
		return false;
	}

	$_SWIFT["user"] = $_swiftuser;

	return $_swiftuser["userid"];
}

/**
* Return the Unique User ID of the current user
*/
function loginShareUserID()
{
	global $_SWIFT;

	if (empty($_SWIFT["user"]["userid"]))
	{
		return false;
	} else {
		return $_SWIFT["user"]["userid"];
	}
}

/**
* Logout the current user
*/
function loginShareLogout()
{
	global $session, $_SWIFT;

	$session->updateSession($_SWIFT["session"]["sessionid"], 0);

	return true;
}

/**
* Load the user credentials into current workspace. The following variables should be declared for proper working:
* userid - User id that is set in the "users" table
* fullname
* email - Array
* password (MD5 Hashed)
* usergroupid - If this is not set, then it will use the default registered user group for this template group
*/
function loginShareLoadUser()
{
	global $dbCore, $_SWIFT, $loginshare;

	if (empty($_SWIFT["session"]["typeid"]))
	{
		$_SWIFT["user"]["loggedin"] = false;
		return false;
	}

	$_user = $loginshare->loadSWIFTUser($_SWIFT["session"]["typeid"]);
	if (!$_user)
	{
		$_SWIFT["user"]["loggedin"] = false;

		return false;
	}

	$_SWIFT["user"] = $_user;

	return true;
}

/**
* Renders the Login Share Form
*/
function renderLoginShareForm()
{
	global $_SWIFT;

	$forms = array();

	$forms[0]["title"] = $_SWIFT["language"]["ldaphostname"];
	$forms[0]["name"] = "adhostname";
	$forms[1]["title"] = $_SWIFT["language"]["ldapport"];
	$forms[1]["name"] = "adport";
	$forms[2]["title"] = $_SWIFT["language"]["ldapbasedn"];
	$forms[2]["name"] = "adbasedn";
	$forms[3]["title"] = $_SWIFT["language"]["ldaprdn"];
	$forms[3]["name"] = "adrdn";
	$forms[4]["title"] = $_SWIFT["language"]["ldappassword"];
	$forms[4]["name"] = "adpassword";

	return $forms;
}
?>